package com.liang.shiro;

import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.liang.exception.CaptchaEmptyException;
import com.liang.exception.CaptchaErrorException;
import com.liang.pojo.Root;
import com.liang.service.RootService;

public class RootRealm2 extends AuthorizingRealm{
	@Autowired
	RootService rootService;
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = principals.getPrimaryPrincipal().toString();
		Set<String> roles = rootService.selectRoleByUsername(username);
		Set<String> permissions = rootService.selectPremissionByUsername(username);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setRoles(roles);
		info.setStringPermissions(permissions);
		return info;
	}

	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		 // 在自定义的认证过滤器中将验证码保存至KaptchaCodeToken中
        // 此处的Token就是认证过滤器中实例化的Token,可以直接强制转换
		CaptchaToken captchaToken=(CaptchaToken)token;
		String captchacode = captchaToken.getCaptchacode();
		if(captchacode==null || "".equals(captchacode)) {
			throw new CaptchaEmptyException();
		}
		// Kaptcha在生成验证码时会将验证码放入SESSION中
        // 默认KEY为KAPTCHA_SESSION_KEY, 可以在Web.xml中配置
		String sessionCaptcha = (String) SecurityUtils.getSubject().getSession().getAttribute("KAPTCHA_SESSION_KEY");
		if(!captchacode.equals(sessionCaptcha)) {
			throw new CaptchaErrorException();
		}
//		String username = capchaToken.getPrincipal().toString();
		String username = captchaToken.getUsername();
//		String username2 = token.getPrincipal().toString();
//		String username3 = ((UsernamePasswordToken) captchaToken).getUsername();
		String username3=captchaToken.getUsername();
		String username4 = captchaToken.getPrincipal().toString();

		System.out.println("++++++++++++++++++++++++"+username);
		System.out.println("++++++++++++++++++++++++"+username3);
		System.out.println("++++++++++++++++++++++++"+username4);
		Root root = rootService.selectRootByUsername(username3);
		if(root==null) {
			return null;
		}else {
	        ByteSource salt = ByteSource.Util.bytes(username3);
	        //封装用户信息，构建AuthenticationInfo对象并返回
	        AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(username3, root.getPassword(),
	                salt,this.getName());
	        return authcInfo;
		}
	}
}
